<?php
namespace Home\Controller;
use Think\Controller;
//下载
class DownloadController extends CommonController {
	private $report_attachment_path = "/Data/report_attachement/";
	private $uid = null;

	public function __construct(){
		parent::__construct();
		$this->uid = session('uid');
	}

	//非ajax操作-报告下载(链接)
	public function fetch(){
		if(empty($this->uid)) redirect('/member/login.html');
		
		//报告编号
		$id = I('post.id',0,'intval');
		if(!is_numeric($id) || !$id) redirect("/report/index.html");

		//获取该下载报告信息
		$ReportModel = D('Report');
		$info = $ReportModel->info($id,$getcontent = false);
		if(!empty($info)){
			//用户权限检查: 1 没下架，免费则直接下载 2 收费且已购买 则直接下载 3 收费但无购买记录则提示“请先购买”
			$status = $info['status'];
			$price = $info['price'];

			if($price > 0 ){//收费
				//是否购买
				$buy_info = $this->checkDownloadPower($id);
				if(empty($buy_info)){
					$this->error("请购买后下载","/report/detail.html?id=".$id);
				}else{
					//不管是否下线，只要购买皆能下载
					$this->downreport($info);
				}
			}else{//免费
				if($status==1){
					//下载
					$this->downreport($info);
				}else{
					$this->error("该报告已下架","/report/index.html");
				}
			}

			redirect("/report/detail.html?id=".$id);
		}else{
			redirect("/report/index.html");
		}
		
	}

	//权限检查
	private function checkDownloadPower($id){
		if(!is_numeric($id) || empty($id)) return null;

		//用户权限检查: 1 免费则直接下载 2收费且已购买 则直接下载 3 收费但无购买记录则提示“请先购买”
		$uid = $this->uid;
		$ReportOrdersModel = D('ReportOrders');
		$info = $ReportOrdersModel->checkExistsBuy($uid,$id);

		return $info;
	}

	//下载文件生成
	private function downreport($info){
		header("Content-type:text/html;charset=utf-8"); 
		$file_name= $info['attachment'];

		//用以解决中文不能显示出来的问题 
		$file_name=iconv("utf-8","gb2312",$file_name);
		$file_path=".".$file_name;
		$download_file_name = iconv("utf-8","gb2312",$info['attachment_name']);
		//首先要判断给定的文件存在与否 
		if(!file_exists($file_path)){ 
			$this->error("改报告文件源不存在",'/report/index.html');
		} 
		
		$fp=fopen($file_path,"r"); 
		$file_size=filesize($file_path); 
		//下载文件需要用到的头 
		Header("Content-type: application/octet-stream"); 
		//Header("Content-type:application/pdf");
		Header("Accept-Ranges: bytes"); 
		Header("Accept-Length:".$file_size); 
		Header("Content-Disposition: attachment; filename=".$download_file_name); 

		$buffer=1024; 
		$file_count=0; 
		//向浏览器返回数据 
		while(!feof($fp) && $file_count<$file_size){ 
		$file_con=fread($fp,$buffer); 
		$file_count+=$buffer; 
		echo $file_con; 
		} 
		fclose($fp);

		//入库-报告下载次数
		$this->addReportUsenum($info['id']);
		exit(); 
	}

	//记录某报告下载人数（次数）
	private function addReportUsenum($report_id = null){
		if(empty($report_id)) return false;
		$reportModel = M('Report');
		$where['id'] = $report_id;
		return $reportModel->where($where)->setInc('use_nums');
	}

}